package com.eshop.message.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.PatternTopic;
import com.eshop.message.redis.listener.RedisKeyExpirationListener;
import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import com.eshop.modules.activity.service.StorePinkService;
import com.eshop.modules.order.service.StoreOrderService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class RedisListenerConfig
{
    private final RedisTemplate<String, String> redisTemplate;
    private final RedisConfigProperties redisConfigProperties;
    private final StoreOrderService storeOrderService;
    private final StorePinkService storePinkService;
    
    @Bean
    RedisMessageListenerContainer container(final RedisConnectionFactory factory) {
        final String topic = StrUtil.format("__keyevent@{}__:expired", new Object[] { this.redisConfigProperties.getDatabase() });
        final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        container.addMessageListener(new RedisKeyExpirationListener(this.redisTemplate, this.redisConfigProperties, this.storeOrderService, this.storePinkService), (Topic)new PatternTopic(topic));
        return container;
    }
    
    public RedisListenerConfig(final RedisTemplate<String, String> redisTemplate, final RedisConfigProperties redisConfigProperties, final StoreOrderService storeOrderService, final StorePinkService storePinkService) {
        this.redisTemplate = redisTemplate;
        this.redisConfigProperties = redisConfigProperties;
        this.storeOrderService = storeOrderService;
        this.storePinkService = storePinkService;
    }
}
